<?php
namespace SixShop\News\Controller\Api;

use think\Response;
use think\Request;
use SixShop\News\Service\NewsService;

class NewsController
{
    private $service;

    public function __construct(NewsService $service)
    {
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $params = $request->get();

        // 兼容：若前端未传 where，而是顶层传 category_id / title，则转为 where 条件
        $where = [];
        if (!empty($params['where']) && is_array($params['where'])) {
            $where = $params['where'];
        }
        // 顶层 category_id 兼容
        if (isset($params['category_id']) && $params['category_id'] !== '') {
            $where['category_id'] = (int) $params['category_id'];
        }
        // 顶层 title 兼容（模糊查询）
        if (isset($params['title']) && $params['title'] !== '') {
            // 具体模糊查询写法由 Go 侧处理，这里仅传递关键字
            $where['title'] = (string) $params['title'];
        }

        // 分页/排序规范化
        $order = $params['order'] ?? ['is_top' => 'desc', 'id' => 'desc'];
        $limit = isset($params['limit']) ? (int) $params['limit'] : 20;
        $page  = isset($params['page']) ? (int) $params['page'] : 1;

        $list = $this->service->getList(
            $where,
            $order,
            $limit,
            $page
        );
        return json($list);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function read($id): Response
    {
        $item = $this->service->getById($id);
        return json($item);
    }

    /**
     * 增加文章阅读数
     *
     * @param  int  $id
     * @return Response
     */
    public function incrementViews($id): Response
    {
        $result = $this->service->incrementViews($id);
        return json($result);
    }
    
    /**
     * Save a new resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $data = $request->post();
        $result = $this->service->create($data);
        return json($result);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id): Response
    {
        $data = $request->put();
        $result = $this->service->update($id, $data);
        return json($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function delete($id): Response
    {
        $result = $this->service->delete($id);
        return json($result);
    }
} 